package com.share.config.jdkproxy;

import com.alibaba.fastjson.JSON;
import com.share.common.common.Result;
import com.share.common.enums.ErrMsgEnum;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成接口的实现类
 */
@Slf4j
public class FeignClientFallbackJDKProxy implements InvocationHandler {
    //代理对象的缓存
    static Map<Object, Object> map = new HashMap<>();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log.info("feign调用发生了熔断,method={},args={}", method.getName(), JSON.toJSON(args));
        return Result.failure(ErrMsgEnum.HYSTRIX_HAPPEN);// 直接返回熔断的结果
    }

    /*获取代理对象*/
    public <T> T getProxy(Class<T> proxyInterface) {
        Object o = map.get(proxyInterface);
        if (o == null) {
            synchronized (proxyInterface) {
                o = map.get(proxyInterface);
                if (o == null) {
                    o = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{proxyInterface}, this);
                    map.put(proxyInterface, o);
                }
            }
        }
        return (T) o;
    }
}
